<?php

namespace App\Services\Index\Elasticsearch;

use App\Services\Service;
use App\Services\Traits\DatabaseElasticsearch;
use App\Models\Elasticsearch\Settlement\Info as SettlementInfo;
use App\Models\Elasticsearch\Order\Wallet as WalletOrder;
use App\Core\Traits\Numeral;
use Helper\Timed;

class ChartService extends Service
{
	use DatabaseElasticsearch, Numeral;

	/**
	 * 概要统计【平台收益】
	 */
	public function amount($request)
	{
		Timed::setForceAbs();
		// $timezone = $request->user()->config->timezoneArr->code;
		$timezone = Timed::getTimeCode();


		$params = ['body' => ['size' => 0, 'track_total_hits' => false]];
		// 筛选【类型】
		$this->makeWhere($params, 'player_type', SettlementInfo::PLAYER_TYPE);
		// 筛选【平台】
		$this->makeWhereOrg($request, $params);
		// 筛选【时间】
		$this->makeWhereLastDays($request, $params, 'end_time', 100);
		// 获取时间参数
		$datetime = $this->getParamArray($request, 'datetime');
		// 统计数据【数据列表】
		$params['body']['aggs']['group'] = [
			'date_histogram' => [
				'field' => 'end_time_at',
				'time_zone' => (preg_replace("/^UTC/", "", $timezone)),
				'calendar_interval' => '1d',
				'format' => 'yyyy-MM-dd',
				'min_doc_count' => 0,
				'extended_bounds' => [
					'min' => $datetime[0] * 1000,
					'max' => $datetime[1] * 1000,
				],
			],
			'aggs' => [
				'usd.gain_player' => [
					'sum' => [
						'field' => 'usd.gain_player',
					]
				],
			],
		];
		// 查询数据
		$results = SettlementInfo::search($params);

		date_default_timezone_set(Timed::getTimezoneName());
		// 制作数据
		return collect(array_map(
			function ($item) {
				return [
					'timed' => $item['key'] / 1000,
					'amount' => $this->makeRound(-$item['usd.gain_player']['value']),
				];
			},
			$results['aggregations']['group']['buckets']
		));
	}

	/**
	 * 统计图【钱包订单】
	 */
	public function wallet($request)
	{
		Timed::setForceAbs();
		$params = ['body' => ['size' => 0, 'track_total_hits' => false]];
		// 筛选【平台】
		$this->makeWhereOrg($request, $params);
		// 筛选【时间】
		$this->makeWhereLastDays1($request, $params, 'created', 10, true);
		// 筛选【状态】
		$this->makeWhere($params, 'status', WalletOrder::STATUS_SUCCEED);

		// 统计数据
		$params = $this->getMakeGroupAggsByTimezone($request, $params);

		// 查询数据
		$results = WalletOrder::search($params);

		date_default_timezone_set(Timed::getJsLocalTimezoneNameByCookie());
		//17点  +8时区 -11时区   昨天22点
		//22点  +8时区 +12时区  明天2点   -3 +8
		// 本地偏移量比如 +08:00 则是 8*3600
		$localOffset = Timed::getSecondsByTimeCode(Timed::getJsLocalTimezoneCodeByCookie());
		// 选择偏移量比如 +12:00 则是 12*3600
		$selectOffset = Timed::getSecondsByTimeCode(Timed::getTimeCode());
		// 本地减去选择取绝对值
		$offset = abs($localOffset - $selectOffset);
		// 这个是什么意思比如现在是16:00 - 00:00 就是已经16个小时了
		$diff = (time() - strtotime(date('Y-m-d')));
		//时差还没到今天，减去一天时间
		$operate = 0;
		// 本地偏移>选择偏移 并且 偏移绝对值 大于 时差
		if ($localOffset > $selectOffset && $offset > $diff) {
			// $operate = 1;
		}
		//当翻到第二天，加一天时间 -3 +8 11小时
		// 本地偏移<选择偏移 并且 偏移绝对值 + 时差 >= 86400
		if ($localOffset < $selectOffset && $diff + $offset >= 86400) {
			$operate = 2;
		}

		date_default_timezone_set(Timed::getTimezoneName());
		foreach ($results['aggregations']['group']['buckets'] as $k => $v) {
			$results['aggregations']['group']['buckets'][$k]['operate'] = $operate;
		}
		// 制作数据
		return collect(array_map(
			function ($item) {
				$timed = $item['key']['timed'];
				if ($item['operate'] == 1) {
					$timed = $item['key']['timed'] - 86400;
				} else if ($item['operate'] == 2) {
					$timed = $item['key']['timed'] + 86400;
				}
				return [
					'timed' => $timed,
					'consume_sum' => $this->makeRound($item['usd.consume_sum']['value']),
					'take_back_sum' => $this->makeRound($item['usd.take_back_sum']['value']),
				];
			},
			$results['aggregations']['group']['buckets']
		));
	}

	/**
	 * @return bool
	 */
	public function selectTimezoneGtLocalTimezone(): bool
	{
		return Timed::getSecondsByTimeCode(Timed::getTimeCode()) > Timed::getSecondsByTimeCode(Timed::getJsLocalTimezoneCodeByCookie());
	}

	/**
	 * @param $request
	 * @param array $params
	 * @return array
	 */
	public function getMakeGroupAggsByTimezone($request, array $params): array
	{
		if ($this->selectTimezoneGtLocalTimezone()) {
			$this->makeGroupAggs($request, $params, 'sum', ['usd.consume_sum', 'usd.take_back_sum'],
				[
					['timed' => ['terms' => ['script' => "doc['created'].value - (doc['created'].value + " . (Timed::getSecondsByTimeCode(Timed::getJsLocalTimezoneCodeByCookie())) . ") % 86400"]]]
				]
			);
		} else {
			$this->makeGroupAggs($request, $params, 'sum', ['usd.consume_sum', 'usd.take_back_sum'],
				[
					['timed' => ['terms' => ['script' => "doc['created'].value - (doc['created'].value + " . (Timed::getSecondsByTimeCode(Timed::getTimeCode())) . ") % 86400"]]]
				]
			);
		}
		return $params;
	}
}
